import { PlayerOptions, VideoSource } from './options'
import { checkVideoType } from './utils'

import videoHtml from '../html/video.html'

export default class Video {
	options: PlayerOptions = undefined as unknown as PlayerOptions
	quality = 0
	el = undefined as unknown as HTMLVideoElement

	constructor(container: HTMLElement, options: PlayerOptions) {
		// 视频类的构造函数
		const videoContainer = container.querySelector('.micro-player-video') as HTMLElement
		videoContainer.outerHTML = videoHtml

		this.quality = options.defaultQuality || 0
		this.el = container.querySelector('.micro-player-video') as HTMLVideoElement

		this.initVideo(options)
	}

	getCurrentSrc(): VideoSource {
		// 获取当前视频源地址
		if (Array.isArray(this.options.src)) {
			return this.options.src[this.quality] as VideoSource
		} else {
			return this.options.src as VideoSource
		}
	}

	initVideo(options: PlayerOptions) {
		// 初始化视频播放器
		if (typeof options.src === 'string') {
			const videoType = checkVideoType(options.src)
			this.options = { ...options, src: { url: options.src, type: videoType } }
		} else if (Array.isArray(options.src)) {
			const srcList = options.src.map(item => {
				if (typeof item === 'string') {
					const videoType = checkVideoType(item)
					return { url: item, type: videoType }
				} else {
					const videoType = checkVideoType(item.url, item.type)
					return { ...item, type: videoType }
				}
			})
			this.options = { ...options, src: srcList }
		} else {
			const videoType = checkVideoType(options.src.url, options.src.type)
			this.options = { ...options, src: { ...options.src, type: videoType } }
		}

		this.el.setAttribute('preload', this.options.preload || 'auto')
		if (this.options.autoPlay) {
			this.el.setAttribute('autoplay', 'true')
		}
		if (this.options.loop) {
			this.el.setAttribute('loop', 'true')
		}
		if (this.options.muted) {
			this.el.setAttribute('muted', 'true')
		}
		if (this.options.poster) {
			this.el.setAttribute('poster', this.options.poster)
		}

		this.el.setAttribute('controls', 'true')

		this.el.setAttribute('src', this.getCurrentSrc()?.url)
	}
}
